/*
 * The MIT License
 *
 * Copyright (c) 2010, Seiji Sogabe
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package hudson.plugins.googlecodetrigger;

import hudson.Util;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.Hudson;
import hudson.model.Run;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import org.acegisecurity.AccessDeniedException;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

/**
 *
 * @author sogabe
 */
public class GooglecodeTriggerAction implements Action {

    private final AbstractProject<?, ?> project;

    private final GooglecodeTrigger trigger;

    public GooglecodeTriggerAction(AbstractProject<?, ?> project, GooglecodeTrigger trigger) {
        this.project = project;
        this.trigger = trigger;
    }

    @Override
    public String getUrlName() {
        return "googlecodetrigger";
    }

    public String getDisplayName() {
        return "GooglecodeTriggerAction";
    }

    public String getIconFileName() {
        return null;
    }

    @SuppressWarnings("PMD.UnusedFormalParameter")
    public void doBuild(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        LOGGER.fine("doBuild called.");
        // Check Post-Commit Authentication Key if specified.
        if (trigger.getKey() == null) {
            // Check security of Hudson self.
            checkPermission(req);
        } else if (!checkAuthenticationKey(req)) {
            LOGGER.severe("Post-Commit Authentication Key is unmatch.");
            throw new AccessDeniedException("Post-Commit Authentication Key is unmatch.");
        }

        String rev = Util.fixEmptyAndTrim(req.getParameter("rev"));

        if (isTriggered(rev)) {
            LOGGER.info("Revision: " + rev + " has already been triggered.");
            throw new AccessDeniedException("Not allowed to build.");
        }

        int delay = project.getDelay(req);
        GooglecodeTriggerCause cause = new GooglecodeTriggerCause(req.getRemoteAddr(), rev);
        project.scheduleBuild(delay, cause);
    }

    private void checkPermission(StaplerRequest req) {
        if (!Hudson.getInstance().isUseSecurity()) {
            LOGGER.fine("No security used.");
            return;
        }
        project.checkPermission(AbstractProject.BUILD);
    }

    private boolean checkAuthenticationKey(StaplerRequest req) {
        String payload = getPayload(req);
        String expecedHash = req.getHeader("Google-Code-Project-Hosting-Hook-Hmac");
        AuthenticationKey key = new AuthenticationKey(trigger.getKey());
        return key.validate(expecedHash, payload);
    }

    private boolean isTriggered(String rev) {
        if (rev == null) {
            return false;
        }
        Run<?, ?> b = project.getLastBuild();
        while (b != null) {
            GooglecodeTriggerCause cause = b.getCause(GooglecodeTriggerCause.class);
            if (cause != null) {
                String r = cause.getRev();
                if (rev.equals(r)) {
                    return true;
                }
            }
            b = b.getPreviousBuild();
        }
        return false;
    }

    private String getPayload(StaplerRequest req) {
        BufferedReader r = null;
        StringBuilder payload = new StringBuilder();
        try {
            r = req.getReader();
            String line;
            while ((line = r.readLine()) != null) {
                payload.append(line);
            }
        } catch (IOException e) {
            //
        } finally {
            closeQuietly(r);
        }
        return payload.toString();
    }

    private void closeQuietly(Closeable c) {
        if (c == null) {
            return;
        }
        try {
            c.close();
        } catch (IOException e) {
            LOGGER.warning(e.getMessage());
        }
    }

    private static final Logger LOGGER = Logger.getLogger(GooglecodeTriggerAction.class.getName());
}
